package cn.wangzg.course0602;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import cn.wangzg.course0602.util.HttpUtil;

public class WanListActivity extends AppCompatActivity {
    private ListView listArticle;
    private ArrayList<Article> articles;
    //private CommonAdapter<Article> adapter;
    private ArticleAdapter adapter;
    //官方建议写法
    static class MyHandler extends Handler {
        // WeakReference to the outer class's instance.
        private WeakReference<WanListActivity> mOuter;

        public MyHandler(WanListActivity activity) {
            mOuter = new WeakReference<WanListActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            WanListActivity outer = mOuter.get();
            if (outer != null) {
                if (msg.what == 1) {
                    String str = (String) msg.obj;
                    //outer.tv_html.setText(str);
                    //outer.adapter.setmDatas(outer.articles);
                }
            }
        }
    }

    private MyHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wan_list);

        autoLogin();
        initView();
        getData();
    }

    private void autoLogin() {
        SharedPreferences sp=getSharedPreferences("wan",MODE_PRIVATE);
        String name = sp.getString("name","");
        String pwd=sp.getString("pwd","");
        //Toast.makeText(this, name+":"+pwd, Toast.LENGTH_SHORT).show();
        //1.如果不登录不允许使用App的话，在此打开登录界面
//        if("".equals(name)) {
//            startActivity(new Intent(this, LoginActivity.class));
//        }
        new Thread() {
            @Override
            public void run() {
                //2.发送post请求
                try {
                    String strUrl = "https://www.wanandroid.com/user/login";
                    String data = "username=" + URLEncoder.encode(name, "utf-8")
                            + "&password=" + URLEncoder.encode(pwd, "utf-8");
                    String s = HttpUtil.doPost(strUrl, data);

                    //获取errorCode，如为0，登录成功，跳转
                    JSONObject object = new JSONObject(s);
                    int errcode = object.optInt("errorCode");
                    String errMsg = object.optString("errorMsg");
                    if (errcode == 0) {
                        getData();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void getData() {
        new Thread() {//new thread
            @Override
            public void run() {
                String strUrl = "https://www.wanandroid.com/article/list/0/json";
                String s = HttpUtil.doGet(strUrl);
                articles = parseArticle(s);
                for (Article a : articles) {
                    System.out.println(a.toString());
                }
                //tv_html.setText(s);
//                Message msg=new Message();
//                msg.what=1;//区分不同的返回值
//                //msg.obj=s;
//                handler.sendMessage(msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //adapter.setmDatas(articles);
                        adapter.setArticles(articles);
                    }
                });
            }
        }.start();
    }

    private ArrayList<Article> parseArticle(String s) {
        ArrayList<Article> list = new ArrayList<>();
        Article article;
        try {
            JSONObject object = new JSONObject(s);
            int errCode = object.optInt("errorCode");
            if (errCode == 0) {
                JSONArray array = object.optJSONObject("data")
                        .optJSONArray("datas");
                for (int i = 0; i < array.length(); i++) {
                    article = new Article();
                    JSONObject obj = array.optJSONObject(i);
                    article.setId(obj.optInt("id"));
                    article.setTitle(obj.optString("title"));
                    article.setShareUser(obj.optString("shareUser"));
                    article.setSuperChapterName(obj.optString("superChapterName"));
                    article.setChapterName(obj.optString("chapterName"));
                    article.setNiceDate(obj.optString("niceDate"));
                    article.setLink(obj.optString("link"));
                    article.setCollect(obj.getBoolean("collect"));
                    list.add(article);
                }
            } else {
                return null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void initView() {
        //handler = new MyHandler(this);
        listArticle = findViewById(R.id.listArticle);
        //使用通用适配器，建议大家掌握，但是考试时不考此内容
//        adapter=new CommonAdapter<Article>(this,null,
//                R.layout.item_article) {
//            @Override
//            public void convert(ViewHolder helper, final Article item) {
//                helper.setText(R.id.textView,item.getTitle());
//                helper.setText(R.id.textView3,item.getShareUser());
//                helper.setText(R.id.textView5,item.getSuperChapterName()
//                +"/"+item.getChapterName());
//                helper.setText(R.id.textView7,item.getNiceDate());
//                helper.getView(R.id.imageView).setSelected(item.isCollect());
//                helper.getView(R.id.imageView).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        v.setSelected(!v.isSelected());
//                        item.setCollect(v.isSelected());
//                    }
//                });
//            }
//        };
        adapter=new ArticleAdapter(this);
        listArticle.setAdapter(adapter);
        //添加Item的单击事件处理
        listArticle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(WanListActivity.this,ReadActivity.class);
                //传递参数
                intent.putExtra("link",articles.get(position).getLink());
                startActivity(intent);
            }
        });
    }
    //添加菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mainmenu,menu);
        return true;
    }
    //添加菜单事件处理
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.login:
                startActivity(new Intent(WanListActivity.this,LoginActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
